const { User } = require("../model")

// 查找用户
async function getUser({ username, password }) {
  const result = await User.findOne({
    where: {
      username,
      password
    }
  })

  return result
}

// 判断用户名是否存在
async function isExistUser(username) {
  const result = await User.findOne({
    where: { username }
  })
  return result
}

// 添加用户
async function createUser({ username, password, avatar }) {
  if (!username || !password) {
    return null
  }
  const data = { username, password }
  if (avatar) {
    data.avatar = avatar
  }

  const result = await User.create(data)
  return result
}

// 添加头像、修改密码
async function updateUser({ id, avatar, password }) {
  if (!id) {
    return null
  }
  const setOpt = {}

  if (avatar) {
    setOpt.avatar = avatar
  }
  if (password) {
    setOpt.password = password
  }
  const result = await User.update(setOpt, {
    where: { id }
  })

  return result
}



module.exports = {
  isExistUser,
  getUser,
  createUser,
  updateUser
}
